package com.appkubes.mall.restful.application.common.basic.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.appkubes.mall.restful.application.common.basic.SmsService;
import com.appkubes.mall.restful.application.common.basic.model.alisms.AliSMSConfigModel;
import com.appkubes.mall.restful.application.common.basic.model.alisms.TemplateParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AliSmsService<T> implements SmsService<T> {

    @Autowired
    private AliSMSConfigModel aliSMMallSystemConfigModel;

    @Override
    public T sendSMS(String mobilePhone, String code, Class<T> clazz) throws Exception {

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(aliSMMallSystemConfigModel.getDefaultProfile(),
                aliSMMallSystemConfigModel.getAccessKeyId(), aliSMMallSystemConfigModel.getAccessKeySecret());

        DefaultProfile.addEndpoint(aliSMMallSystemConfigModel.getRegion(),
                aliSMMallSystemConfigModel.getProduct(),
                aliSMMallSystemConfigModel.getDomain());

        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest smsRequest = new SendSmsRequest();

        TemplateParam param = new TemplateParam();
        param.setCode(code);
        param.setProduct(aliSMMallSystemConfigModel.getTemplateParamProduct());

        //必填，设置短信接收号码
        smsRequest.setPhoneNumbers(mobilePhone);
        //必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        smsRequest.setSignName(aliSMMallSystemConfigModel.getSignName());
        //必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        smsRequest.setTemplateCode(aliSMMallSystemConfigModel.getTemplateCode());
        //可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        smsRequest.setTemplateParam(JSONObject.toJSONString(param, false));

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //smsRequest.setSmsUpExtendCode("90998");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //smsRequest.setOutId("myoutid");
        SendSmsResponse smsResponse = acsClient.getAcsResponse(smsRequest);
        return (T) smsResponse;
    }
}
